// pages/category/index.js
import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //左侧菜单列表：
    leftMenuList: [],
    //
    currentIndex: 0,
    //右侧内容：
    rightContent: [],
    //
    initTop: 0,
    //接口返回的数据：
    cates: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const cates = wx.getStorageSync("cates");
    if((!cates) || (Date.now() - cates.time > 10000)){
      this.getCates();
    }else{
      this.cates = cates.data;
      let leftMenuList = this.cates.map(v => v.cat_name);
      let rightContent = this.cates[0].children;
      this.setData({
        leftMenuList,
        rightContent
      });
    }
  },

  /**
   * 获取分类数据
   */
  getCates(){
    request({
      url: "/categories"
    })
    .then(res => {
      // console.log(res);
      this.cates = res.data.message;
      wx.setStorageSync("cates", {time: Date.now(), data: this.cates})

      let leftMenuList = this.cates.map(v => v.cat_name);
      let rightContent = this.cates[0].children;
      this.setData({
        leftMenuList,
        rightContent
      });
    })
    .catch(err => {console.log(err);});
  },

  handleItemTap(e){
    const { index } = e.currentTarget.dataset;
    //es6解构语法糖，等同于：const i = e.currentTarget.dataset.index
    let rightContent = this.cates[index].children;
    this.setData({
      currentIndex: index,
      rightContent,
      initTop: 0
    });
  }

})